package com.newlink.building.login.ui

import android.util.Log
import android.view.View
import com.newlink.building.login.R
import com.newlink.building.login.common.Module_Login_Constant
import com.newlink.building.login.databinding.ActivityForgetPasswordBinding
import com.newlink.building.login.event.ResetPwdEvent
import com.newlink.building.login.event.SetKitPwdEvent
import com.newlink.building.login.event.VerifyCodeEvent
import com.newlink.building.login.event.VerifyEmailEvent
import com.newlink.building.login.event.VerifySMSCodeEvent
import com.newlink.building.login.event.VerifySMSEvent
import com.newlink.building.login.ui.fragments.Module_Login_KitSetPasswordFragment
import com.newlink.building.login.ui.fragments.Module_Login_SetPasswordFragment
import com.newlink.building.login.ui.fragments.Module_Login_VerifyCodeFragment
import com.newlink.building.login.ui.fragments.Module_Login_VerifyEmailFragment
import com.newlink.building.login.ui.fragments.Module_Login_VerifyMobileFragment
import com.newlink.building.login.ui.fragments.Module_Login_VerifySMSCodeFragment
import com.newlink.building.common_base.base.NL_BaseActivity
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @Author: Jake
 * @Date: 2022/10/27
 * @Description: 忘记密码界面，负责管理密码重置流程中的多个Fragment
 */
class Module_Login_ForgetPwdEmailActivityNL : NL_BaseActivity() {

    // 视图绑定实例
    private lateinit var binding: ActivityForgetPasswordBinding

    // 当前用户类别，默认为1
    var mUserCategory: Int = 1

    // Fragment实例，按需创建和复用
    private var verifyEmailFragment: Module_Login_VerifyEmailFragment? = null
    private var setPasswordFragment: Module_Login_SetPasswordFragment? = null
    private var verifyCodeFragment: Module_Login_VerifyCodeFragment? = null
    private var verifyMobileFragment: Module_Login_VerifyMobileFragment? = null
    private var verifySMSCodeFragment: Module_Login_VerifySMSCodeFragment? = null
    private var kitSetPasswordFragment: Module_Login_KitSetPasswordFragment? = null

    /**
     * 绑定布局文件并返回根视图。
     */
    override fun attachLayoutRes(): View {
        binding = ActivityForgetPasswordBinding.inflate(layoutInflater)
        return binding.root
    }

    /**
     * 初始化数据，获取Intent中传入的用户类别。
     */
    override fun initData() {
        mUserCategory =
            intent.getIntExtra(
                com.newlink.building.common_base.constant.Base_Constant.KEY_USER_CATEGORY,
                1
            )
    }

    /**
     * 初始化视图组件和设置初始Fragment。
     */
    override fun initView() {
        // 设置返回按钮的点击事件，点击后执行返回操作
        binding.topBarBack.setOnClickListener {
            onBackPressed()
        }
        // 初始化并显示VerifyEmailFragment作为起始Fragment
        verifyEmailFragment = Module_Login_VerifyEmailFragment.getInstance()
        supportFragmentManager.beginTransaction()
            .replace(
                R.id.forget_pwd_content,
                verifyEmailFragment!!,
                Module_Login_Constant.Type.RESET_INPUT_EMAIL
            )
            .commit()
    }

    /**
     * 显示指定类型的Fragment。
     * @param fragmentType 要显示的Fragment类型常量。
     * @param param 传递给Fragment的参数，如邮箱或手机号。
     */
    fun showFragment(fragmentType: String, param: String) {
        Log.e("ForgetPwdEmailActivity", "[$localClassName] -> showFragment : $fragmentType")
        val transaction = supportFragmentManager.beginTransaction()
        hideAllFragments(transaction) // 隐藏当前所有Fragment

        when (fragmentType) {
            Module_Login_Constant.Type.RESET_INPUT_EMAIL -> {
                if (verifyEmailFragment == null) {
                    verifyEmailFragment = Module_Login_VerifyEmailFragment.getInstance()
                    transaction.add(R.id.forget_pwd_content, verifyEmailFragment!!)
                } else {
                    transaction.show(verifyEmailFragment!!)
                }
            }

            Module_Login_Constant.Type.RESET_VERIFY -> {
                if (verifyCodeFragment == null) {
                    verifyCodeFragment = Module_Login_VerifyCodeFragment.getInstance(param)
                    transaction.add(R.id.forget_pwd_content, verifyCodeFragment!!)
                } else {
                    transaction.show(verifyCodeFragment!!)
                }
            }

            Module_Login_Constant.Type.RESET_ACCOUNT -> {
                if (setPasswordFragment == null) {
                    setPasswordFragment = Module_Login_SetPasswordFragment.getInstance(param)
                    transaction.add(R.id.forget_pwd_content, setPasswordFragment!!)
                } else {
                    transaction.show(setPasswordFragment!!)
                }
            }

            Module_Login_Constant.Type.RESET_VERIFY_MOBILE -> {
                if (verifyMobileFragment == null) {
                    verifyMobileFragment = Module_Login_VerifyMobileFragment.getInstance()
                    transaction.add(R.id.forget_pwd_content, verifyMobileFragment!!)
                } else {
                    transaction.show(verifyMobileFragment!!)
                }
            }

            Module_Login_Constant.Type.RESET_VERIFY_SMS -> {
                if (verifySMSCodeFragment == null) {
                    verifySMSCodeFragment = Module_Login_VerifySMSCodeFragment.getInstance(param)
                    transaction.add(R.id.forget_pwd_content, verifySMSCodeFragment!!)
                } else {
                    transaction.show(verifySMSCodeFragment!!)
                }
            }

            Module_Login_Constant.Type.RESET_ACCOUNT_SMS -> {
                if (kitSetPasswordFragment == null) {
                    kitSetPasswordFragment = Module_Login_KitSetPasswordFragment.getInstance(param)
                    transaction.add(R.id.forget_pwd_content, kitSetPasswordFragment!!)
                } else {
                    transaction.show(kitSetPasswordFragment!!)
                }
            }
        }
        transaction.commit()
    }

    /**
     * 隐藏当前Activity中所有Fragment。
     * @param transaction Fragment事务对象。
     */
    private fun hideAllFragments(transaction: androidx.fragment.app.FragmentTransaction) {
        verifyEmailFragment?.let { transaction.hide(it) }
        verifyCodeFragment?.let { transaction.hide(it) }
        setPasswordFragment?.let { transaction.hide(it) }
        verifyMobileFragment?.let { transaction.hide(it) }
        verifySMSCodeFragment?.let { transaction.hide(it) }
        kitSetPasswordFragment?.let { transaction.hide(it) } // 确保隐藏了所有Fragment
    }

    // --- EventBus 订阅方法 ---

    /**
     * 订阅 VerifyEmailEvent，当邮箱验证成功后跳转到验证码输入Fragment。
     * @param event 邮箱验证事件，包含已验证的邮箱。
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEmailVerified(event: VerifyEmailEvent) {
        if (event.email.isNotEmpty()) {
            showFragment(Module_Login_Constant.Type.RESET_VERIFY, event.email)
        }
    }

    /**
     * 订阅 VerifyCodeEvent，当验证码验证成功后跳转到设置密码Fragment。
     * @param event 验证码事件，包含已验证的邮箱。
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onVerificationCodeSucceeded(event: VerifyCodeEvent) {
        if (event.email.isNotEmpty()) {
            showFragment(Module_Login_Constant.Type.RESET_ACCOUNT, event.email)
        }
    }

    /**
     * 订阅 ResetPwdEvent，当密码重置成功后结束当前Activity。
     * @param event 密码重置事件，tag为true表示成
     *
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onPasswordResetCompleted(event: ResetPwdEvent) {
        if (event.tag) {
            finish()
        }
    }

    /**
     * 订阅 VerifySMSCodeEvent，当短信验证码验证成功后跳转到设置密码Fragment（针对手机号）。
     * @param event 短信验证码事件，包含已验证的手机号。
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onSMSCodeVerified(event: VerifySMSCodeEvent) {
        if (event.phone.isNotEmpty()) {
            showFragment(
                Module_Login_Constant.Type.RESET_ACCOUNT_SMS,
                event.phone
            ) // 注意：这里根据原逻辑是跳转到SET_ACCOUNT_SMS
        }
    }

    /**
     * 订阅 VerifySMSEvent，当手机号验证成功后跳转到设置密码Fragment。
     * @param event 手机号验证事件，包含已验证的手机号。
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMobileVerified(event: VerifySMSEvent) {
        showFragment(Module_Login_Constant.Type.RESET_ACCOUNT, event.mobile)
    }

    /**
     * 订阅 SetKitPwdEvent，当Kit密码设置成功后结束当前Activity。
     * @param event Kit密码设置事件，tag为true表示成功。
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onKitPasswordSetCompleted(event: SetKitPwdEvent) {
        if (event.tag) {
            finish()
        }
    }
}